use std::fmt;
use axum::Json;
use serde_json::{ json, Value };
use serde::{ Deserialize, Serialize };
// 自定义一个BusinessError业务错误类型
pub struct SystemError {
    code: usize, // 根据自己需求定义属性，这里定义一个业务错误码
}

// 实现 Display，根据错误码显示不同的错误信息
impl fmt::Display for SystemError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // 不同的错误码，输出不同的错误信息
        let err_msg = match self.code {
            201 => "未登录，请登录！",
            202 => "登录过期",
            203 => "用户名或密码不正确",
            204 => "用户不存在",
            300 => "数据为空",
            301 => "操作失败",
            302 => "必选参数必须是数字，且不能为空",
            303 => "该菜单存在子菜单，不允许删除",
            304 => "该数据已不存在",
            404 => "接口不存在",
            _ => "未知错误",
        };
        write!(f, "{}", err_msg)
    }
}

// 实现 Debug，打印错误时，输出的错误信息
impl fmt::Debug for SystemError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "SystemError {{ code: {} }}", self.code)
    }
}

// 触发 SystemError 错误的函数
pub fn output(code:usize) -> Result<(), SystemError> { Err(SystemError { code: code }) }

#[derive(Debug, Serialize, Deserialize)]
pub struct Data<T> {
    code: usize,
    msg: String,
    data: Option<T>,
}
/* —————————————————————————————————————————————————————————————————— 结构体模式 ——————————————————————————————————————————————————————————————————*/ 
// pub fn check<T>(code:usize, ok_data:T) -> Json<Data<T>> { if code == 200 { ok(ok_data) }else{ no(code) } }
// 成功返回
// pub fn ok<T>(ok_data:T) -> Json<Data<T>> { Json(Data { code: 200, msg: "ok".to_owned(), data: Some(ok_data) }) }
// 失败返回
// pub fn fail<T>(code:usize) -> Json<Data<T>> { 
//     match output(code) {
//         Err(e) => {
//             Json(Data { code: code, msg: e.to_string(), data: None })
//         },
//         _ => {
//             Json(Data { code: code, msg: String::from("其它错误"), data: None })
//         }
//     }
// }
// 自定义错误消息返回
// pub fn err<T>(code:usize, msg:String) -> Json<Data<T>> { Json(Data { code: code, msg: msg, data: None }) }
/* —————————————————————————————————————————————————————————————————— 转换成 Json 格式 ——————————————————————————————————————————————————————————————————*/ 
// 成功返回
pub fn data_(data:Value) -> Json<Value> { Json(json!({ "code": 200, "msg": "ok", "data": data })) }
pub fn data(rs:Value) -> Result<Json<Value>, Json<Value>> { Ok( data_(rs) ) }

pub fn ok_msg_<T: Into<String>>(msg: T) -> Json<Value> { Json(json!({ "code": 200, "msg": msg.into() })) }
pub fn ok_msg<T: Into<String>>(msg: T) -> Result<Json<Value>, Json<Value>> { Ok( ok_msg_(msg) ) }

pub fn ok_() -> Json<Value> { Json(json!({ "code": 200, "msg": "ok" })) }
pub fn ok() -> Result<Json<Value>, Json<Value>> { Ok( ok_() ) }
// 固定错误
pub fn fail_(code:usize) -> Json<Value> {
    match output(code) {
        Err(e) => {
            Json(json!({ "code": code, "msg": e.to_string() }))
        },
        _ => {
            Json(json!({ "code": code, "msg": "其它错误" }))
        }
    }
}
pub fn fail(code:usize) -> Result<Json<Value>, Json<Value>> { Ok( fail_(code) ) }
// 逻辑错误
pub fn err_<T: Into<String>>(msg:T) -> Json<Value> { Json(json!({ "code": 101, "msg": msg.into() })) }
pub fn err<T: Into<String>>(msg:T) -> Result<Json<Value>, Json<Value>> { Err( err_(msg) ) }

pub fn err_code_msg_<T: Into<String>>(code:usize,msg:T) -> Json<Value> { Json(json!({ "code": code, "msg": msg.into() })) }
pub fn err_code_msg<T: Into<String>>(code:usize,msg:T) -> Result<Json<Value>, Json<Value>> { Err( err_code_msg_(code, msg) ) }
// 系统错误
pub fn sys_<T: Into<String>>(msg: T) -> Json<Value> { Json(json!({ "code": 205, "msg": msg.into() })) }
pub fn sys<T: Into<String>>(msg:T) -> Result<Json<Value>, Json<Value>> { Err( sys_(msg) ) }
/* —————————————————————————————————————————————————————————————————— 解析 Result ——————————————————————————————————————————————————————————————————*/
pub fn send<E:ToString>( result:Result<Value, E> ) -> Result<Json<Value>, Json<Value>>{
    match result  {
        Ok(f) => data(json!(f)),
        Err(e) => sys(e.to_string())
    }
}
pub fn send_obj<E:ToString>( result:Result<Value, E> ) -> Result<Json<Value>, Json<Value>>{
    match result  {
        Ok(f) => data(f),
        Err(e) => sys(e.to_string())
    }
}
// 返回  Option<Vaue>
pub fn send_op_obj<E:ToString>( result:Result<Option<Value>, E> ) -> Result<Json<Value>, Json<Value>>{
    match result  {
        Ok(f) => data(json!(f)),
        Err(e) => sys(e.to_string())
    }
}
pub fn send_ext_obj<E:ToString>( rows:Result<Vec<Value>, E>, ext: Result<Option<Value>, E>) -> Result<Json<Value>, Json<Value>>{
    let mut d = json!({});
    match rows  {
        Ok(f) => {
            d["rows"] = json!(f);
            match ext {
                Ok(t) => {
                    d["ext"] = json!(t);
                    data(d)
                },
                Err(e) => sys(e.to_string())
            }
        },
        Err(e) => sys(e.to_string())
    }
}
// 成功返回
pub fn send_arr<E:ToString>( result:Result<Vec<Value>, E> ) -> Result<Json<Value>, Json<Value>>{
    match result  {
        Ok(f) => data(json!(f)),
        Err(e) => sys(e.to_string())
    }
}
pub fn send_ok<T, E:ToString>( result:Result<T, E> ) -> Result<Json<Value>, Json<Value>>{
    match result {
        Ok(_f) => ok(),
        Err(e) => sys(e.to_string())
    }
}
pub fn send_bus( result:Result<(), Json<Value>> ) -> Result<Json<Value>, Json<Value>>{
    match result {
        Ok(_f) => ok(),
        Err(e) =>  Err(e)
    }
}
pub fn send_test(v:Value) -> Result<Json<Value>, Json<Value>>{
    data(v)
}
pub fn send_null() -> Result<Json<Value>, Json<Value>>{
    data(json!(null))
}